package com.ganjingcun.roma.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by GanJc on 2016/4/16.
 */
@Controller
@RequestMapping("/login")
public class LoginController {



    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome() {
        return "login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String printWelcome(String username,String password) {
        System.out.println(username);
        System.out.println(password);
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //登录
//        DefaultPasswordService service = new DefaultPasswordService();
//        String encryptPassword = service.encryptPassword(password);
//        System.out.println(encryptPassword);

//        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
//        Object salt = rng.nextBytes();
        // Now hash the plain-text password with the random salt and multiple
        // iterations and then Base64-encode the value (requires less space than Hex):
//        String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt,1024).toBase64();
        String hashedPasswordBase64 = new Sha256Hash(password, "",1024).toBase64();
        System.out.println(hashedPasswordBase64);

        UsernamePasswordToken token = new UsernamePasswordToken(username, hashedPasswordBase64);
        try{
            subject.login(token);
        }catch (AuthenticationException e){
            LOG.error("登录失败!",e);

        }
        LOG.info("登录成功!hello {}",subject.getPrincipal());
        return "letgo/index";
    }

//    private void generatePassword(User user, String plainTextPassword) {
//        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
//        Object salt = rng.nextBytes();
//
//        // Now hash the plain-text password with the random salt and multiple
//        // iterations and then Base64-encode the value (requires less space than Hex):
////        String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt,1024).toBase64();
//        String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, "",1024).toBase64();
//
//    }

}
